package com.quanquan.user.configBeans;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import utils.DecriptUtils;
import utils.Request;
import utils.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class Weixin {

    @Value("${wx-params.id}")
    private  String appid;

    @Value("${wx-params.secret}")
    private  String secret;

    @Value("${wx-params.jsapiticket}")
    private  String jsapiticket;


	@Autowired
	private StringRedisTemplate redisTemplate;
	

	public String createOauthUrlForCode(String redirectUri) {
		try {
			redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return new StringBuffer().append("https://open.weixin.qq.com/connect/oauth2/authorize?").append("appid=")
				.append(appid).append("&redirect_uri=").append(redirectUri)
				.append("&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect").toString();
	}

	public String getOpenidFromCode(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appid", appid);
		params.put("secret", secret);
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		String result = Request.sendGet(url, params);
		JSONObject jb = JSON.parseObject(result);
		String openid = jb.getString("openid");
		if (StringUtils.isEmpty(openid)) {
			return "";
		}
		return openid;
	}



	public SignPackage getSignPackage(String url,String accessToken) {
		String jsapiTicket = getJsApiTicket(accessToken);
		Long timestamp = System.currentTimeMillis() / 1000;
		String nonceStr = StringUtils.createNonceStr(16);

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		String string = new StringBuffer().append("jsapi_ticket=").append(jsapiTicket).append("&noncestr=")
				.append(nonceStr).append("&timestamp=").append(timestamp).append("&url=").append(url).toString();

		String signature = DecriptUtils.SHA1(string);
		SignPackage signPackage = new SignPackage();
		signPackage.setAppId(appid);
		signPackage.setNonceStr(nonceStr);
		signPackage.setTimestamp(timestamp);
		signPackage.setUrl(url);
		signPackage.setSignature(signature);
		signPackage.setRawString(string);
		return signPackage;
	}
//
//	public static String getSign(Object request) throws Exception {
//		Class<?> clz = request.getClass();
//		Field[] fields = clz.getDeclaredFields();
//		Map<String, String> paramsMap = new TreeMap<String, String>();
//		for (Field field : fields) {
//			if("sign".equals(field.getName())){
//				continue;
//			}
//			Method m = (Method) request.getClass().getMethod("get" + getMethodName(field.getName()));
//			Object value=m.invoke(request);
//			if(value==null)
//				continue;
//			String k=field.getName();
//			String v=k+"="+value;
//			paramsMap.put(k, v);
//		}
//
//		String sign=String.join("&",paramsMap.values());
//		return sign;
//	}
//
//	private static String getMethodName(String fildeName) throws Exception {
//		byte[] items = fildeName.getBytes();
//		items[0] = (byte) ((char) items[0] - 'a' + 'A');
//		return new String(items);
//	}
//
	private String getJsApiTicket(String accessToken) {
        String jsApiTicket = redisTemplate.opsForValue().get(jsapiticket);
        if(StringUtils.isNotEmpty(jsApiTicket)){
            return jsApiTicket;
        }

		String url = new StringBuffer()
				.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=")
				.append(accessToken).append("&secret=").append(secret).toString();
		String result = Request.sendGet(url, null);
		JSONObject jb = JSON.parseObject(result);
		if (!jb.containsKey("ticket")) {
			return "";
		}
		String ticket = jb.getString("ticket");
		if (StringUtils.isEmpty(ticket)) {
			return "";
		}
		redisTemplate.opsForValue().set(jsapiticket, ticket, 100, TimeUnit.MINUTES);
		return ticket;
	}
//
//	/**
//	 * 获取模板列表 获取已添加至帐号下所有模板列表，可在微信公众平台后台中查看模板列表信息
//	 *
//	 * @return
//	 */
//	public AllPrivateTemplate getAllPrivateTemplate() {
//		String url = new StringBuffer()
//				.append("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=")
//				.append(this.getAccessToken()).toString();
//		String result = Request.sendGet(url, null);
//		AllPrivateTemplate templates = JSON.parseObject(result, AllPrivateTemplate.class);
//		return templates;
//	}
//
//	/**
//	 * 发送模板消息
//	 *
//	 * @param requestBody
//	 * @return
//	 */
//	public SendResponse sendTemplateMessage(TemplateMessageRequest requestBody) {
//		String url = new StringBuffer().append("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=")
//				.append(getAccessToken()).toString();
//		String result = Request.postJson(url, requestBody,true);
//		return JSON.parseObject(result, SendResponse.class);
//
//	}
//
//	public UnifiedorderResponse unifiedorder(UnifiedorderRequest unifiedorderRequest) throws Exception{
//		unifiedorderRequest.setAppid(config.getAppid());
//		unifiedorderRequest.setMch_id(config.getMchId());
//		unifiedorderRequest.setNonce_str(StringUtils.createNonceStr(32));
//		unifiedorderRequest.setSign_type("MD5");
//		try {
//			unifiedorderRequest.setSign(DecriptUtils.MD5(getSign(unifiedorderRequest)+"&key="+config.getMchSecret()));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		String str=WeixinXMLUtils.toXML(unifiedorderRequest);
//		String url="https://api.mch.weixin.qq.com/pay/unifiedorder";
//		String result=Request.postXml(url, str);
//		return WeixinXMLUtils.parseObject(UnifiedorderResponse.class, result);
//	}
//
//	public Map<String,String> getJsApiParameters(String prepayId){
//		Map<String,String> params=new TreeMap<String,String>();
//		Map<String,String> paramsMap=new TreeMap<String,String>();
//		String nonceStr = StringUtils.createNonceStr(32);
//		params.put("appId", config.getAppid());
//		paramsMap.put("appId", "appId="+config.getAppid());
//		params.put("timeStamp", System.currentTimeMillis()/1000+"");
//		paramsMap.put("timeStamp", "timeStamp="+System.currentTimeMillis()/1000+"");
//		params.put("nonceStr", nonceStr);
//		paramsMap.put("nonceStr", "nonceStr="+nonceStr);
//		params.put("package", new StringBuffer().append("prepay_id=").append(prepayId).toString());
//		paramsMap.put("package","package="+ new StringBuffer().append("prepay_id=").append(prepayId).toString());
//		params.put("signType", "MD5");
//		paramsMap.put("signType", "signType=MD5");
//		String sign=String.join("&",paramsMap.values())+"&key="+config.getMchSecret();
//		params.put("paySign", DecriptUtils.MD5(sign));
//		return params;
//	}
//
//	public RefundrResponse refundr(RefundrRequest request) throws Exception{
//		request.setAppid(config.getAppid());
//		request.setMch_id(config.getMchId());
//		request.setNonce_str(StringUtils.createNonceStr(32));
//		try {
//			request.setSign(DecriptUtils.MD5(getSign(request)+"&key="+config.getMchSecret()));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		String url="https://api.mch.weixin.qq.com/secapi/pay/refund";
//		File file=new File("/var/cert/apiclient_cert.p12");
//		InputStream certStream=new FileInputStream(file);
//		String result=Request.postXml(url,WeixinXMLUtils.toXML(request),config.getMchId(),certStream);
//		return WeixinXMLUtils.parseObject(RefundrResponse.class, result);
//
//	}

}
